package com.yan.furns.filter;

import com.yan.furns.entity.Member;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Yzb
 * @version 1.0
 */
public class AuthFilter implements Filter {
	private List<String> excludedUrls;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String strExcludedUrls = filterConfig.getInitParameter("excludedUrls");
		String[] splitUrls = strExcludedUrls.split(",");
		excludedUrls = Arrays.asList(splitUrls);
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//		System.out.println("AuthFilter doFilter");
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String servletPath = request.getServletPath();
//		System.out.println("AuthFilter.doFilter: " + servletPath);
		if (!excludedUrls.contains(servletPath)) {
			Member member = (Member) request.getSession().getAttribute("member");
			if (member == null) {
				request.getRequestDispatcher("/views/member/login" +
						".jsp").forward(request, servletResponse);
				return;
			}
		}
		filterChain.doFilter(request, servletResponse);
	}

	@Override
	public void destroy() {

	}
}
